﻿using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using NanoMvvm.Xaml;

namespace NanoMvvm
{
    public static class WorkspaceService
    {
        private static readonly WorkspaceRegistry Registry = new WorkspaceRegistry();

        internal static void WorkspaceActivated(WorkspaceViewModel wvm)
        {
            if (!NanoMvvmFramework.IsInitialized || wvm == null)
            {
                return;
            }

            OnWorkspaceActivation(wvm);
        }

        internal static void WorkspaceDeactivated(WorkspaceViewModel wvm)
        {
            if (!NanoMvvmFramework.IsInitialized || wvm == null)
            {
                return;
            }

            OnWorkspaceDeactivation(wvm);
        }

        private static void OnWorkspaceActivation(WorkspaceViewModel wvm)
        {
            var vmType = wvm.GetType();

            if (Registry.Contains(vmType))
            {
                var record = Registry[vmType];

                if (record.ViewType == null)
                {
                    return;
                }

                ViewManager.SetupView(wvm, record.ViewType);
            }
            else
            {
                WorkspaceViewDesignator record = null;

                try
                {
                    record = NanoMvvmFramework.Instance.Resources.FindResources<WorkspaceViewDesignator>().LastOrDefault(d => d.ViewModelType == vmType);
                }
                catch (Exception ex)
                {
                    Trace.WriteLine("Error finding workspace resources: " + ex.Message);
                    NanoMvvmFramework.Instance.Shutdown();
                }

                if (record != null)
                {
                    Registry.Add(record);

                    ViewManager.SetupView(wvm, record.ViewType);
                }
                else
                {
                    Trace.WriteLine("View for workspace " + vmType + " view model not found.");

                    Registry.Add(new WorkspaceViewDesignator { ViewModelType = vmType, ViewType = null });
                }
            }
        }

        private static void OnWorkspaceDeactivation(WorkspaceViewModel wvm)
        {
            var vmType = wvm.GetType();

            if (!Registry.Contains(vmType))
            {
                return;
            }

            ViewManager.TearDownView(wvm);
        }

        private class WorkspaceRegistry : KeyedCollection<Type, WorkspaceViewDesignator>
        {
            protected override Type GetKeyForItem(WorkspaceViewDesignator item)
            {
                return item.ViewModelType;
            }
        }
    }
}